package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.comment.R;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.target.TargetBaseData;
import com.xinchuang.entity.targetSystem.FontTable;
import com.xinchuang.entity.targetSystem.target.SystemIndex;
import com.xinchuang.exception.CustomException;
import com.xinchuang.mapper.targetSystem.*;
import com.xinchuang.entity.targetSystem.Zone;
import com.xinchuang.entity.targetSystem.object.SystemsAdd;
import com.xinchuang.entity.targetSystem.system.*;
import com.xinchuang.entity.targetSystem.target.TargetData;
import com.xinchuang.entity.targetSystem.target.TargetIndexList;
import com.xinchuang.entity.targetSystem.target.TargetInfo;
import com.xinchuang.mapper.targetSystem.target.SystemsElseMapper;
import com.xinchuang.mapper.targetSystem.target.SystemsRangeMapper;
import com.xinchuang.mapper.targetSystem.target.SystemsRangeTypeMapper;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.target.TargetBaseDataService;
import com.xinchuang.service.targetSystem.*;
import com.xinchuang.service.targetSystem.target.SystemIndexService;
import com.xinchuang.service.targetSystem.target.SystemsElseService;
import com.xinchuang.util.FileElseUtil;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import com.xinchuang.entity.targetSystem.system.SystemsMaster;
import com.xinchuang.entity.targetSystem.system.SystemsRelationship;
import com.xinchuang.utils.RedisName;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName
 * @Description:
 * @auther xukl
 * @data 2021/3/30  16:41
 * @Version V1.0
 */
@Service(value = "systemService")
public class SystemsServiceImpl implements SystemsService {

    private SnowflakeIdWorker snow = new SnowflakeIdWorker(1, 1);

    @Resource
    private SystemsMasterMapper systems;

    @Resource
    private SystemsRelationMapper systemsRelationMapper;

    @Resource
    private SystemsRelationshipMapper systemsRelationshipMapper;

    @Resource
    private SystemsMasterMapper systemsMasterMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TargetMapper targetMapper;

    @Resource
    private BlowMapper blowMapper;

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private KnowMapper knowMapper;

    @Resource
    private SystemElseService systemElseService;

    @Resource
    private SystemsElseService systemsElseService;

    @Resource
    private SystemsRangeMapper systemsRangeMapper;

    @Resource
    private SystemsRangeTypeMapper systemsRangeTypeMapper;

    @Resource
    private SystemEmulateDataMapper systemEmulateDataMapper;

    @Resource
    private RedisUseService redisUseService;

    @Resource
    private AsyncService asyncService;

    @Resource
    private SystemsSceneMapper systemsSceneMapper;

    @Resource
    private SystemsDynamicService systemsDynamicService;

    private static final String typeIndex = "type-index-";

    private static final String systemIndex = "system-index-";

    /**
     * 新增体系关系
     *
     * @param sysId
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> saveRelationship(String sysId, List<SystemsRelationship> list) {
        if (null == sysId) {
            return ResultUtil.error(50003, ResultEnum.getByValue(50003));
        }
        if (systemsRelationshipMapper.findBySysId(sysId) != null || !systemsRelationshipMapper.findBySysId(sysId).isEmpty()) {
            if (systemsRelationshipMapper.deleteBySysId(sysId) == 0) {
                return ResultUtil.error(500, ResultEnum.getByValue(500));
            }
        }
        for (SystemsRelationship systemsRelationship : list) {
            systemsRelationship.setSysShipId(snow.nextId() + "");
            systemsRelationship.setSysId(sysId);
            systemsRelationshipMapper.save(systemsRelationship);
        }
        return ResultUtil.success("体系关系保存成功");
    }

    @Override
    public Result initAddSystem(String status) {
        Map<String, Object> map = new HashMap<>();
        switch (status) {
            case "system":
                map.put("sId", snow.nextId() + "");
                break;
            case "rapex":
                map.put("sysId", snow.nextId() + "");
                break;
        }
        return ResultUtil.success("初始化成功", map);
    }

    @Override
    public Result selectTypePullDown(List<String> typeIds) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(typeIds)) {
            List<TargetType> type = targetMapper.selectTypeList(typeIds);
            for (TargetType t : type) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", t.getTypeId());
                map.put("typeName", t.getTypeName());
                map.put("hiden", true);
                resultList.add(map);
            }
        }
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    public Result selectSystemWaitTarget(String sysId, String keyword) {
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        //查询已选择的目标
        List<String> targetIds = new ArrayList<>();
        String key = keyWordSystem.getVERSION() + "systems" + sysId;
        Set<Object> set = null;
        if (redisUtil.hasKey(key)) {
            set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
        //查询不包含在系统的目标信息
        List<TargetData> targetDataList = targetMapper.selectNotSystemTargets(keyword);
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(targetDataList)) {
            for (TargetData targetData : targetDataList) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("icon", StringUtils.isNotBlank(targetData.getIcon()) ? this.keyWordSystem.getSERVER_URL() + targetData.getIcon() : null);
                //处理已选择目标
                if (targetIds.contains(targetData.getTargetId())) {
                    continue;
                }
//                if (targetIds.contains(targetData.getTargetId())) {
//                    map.put("sign", 1);
//                } else {
//                    map.put("sign", 0);
//                }
                list.add(map);
            }
        }
        resultMap.put("targetList", list);
        return ResultUtil.success("查询成功", resultMap);
    }


    @Override
    public Result addChoiceTarget(
            String sysId, int type,
            List<String> targetArray,
            List<String> systemArray
    ) {
        //缓存类型选择列表key
        String typeKey = "systems_target_type_" + sysId;
        //缓存目标列表
        String targetKey = "system_list_" + sysId;
        //缓存已选独立目标列表
        String onKey = "system_target_list_" + sysId;
        //缓存体系集合类型
        String systemsTypeKey = "system_type_" + sysId;
        String t = FileElseUtil.getObjectToString(redisUtil.get(systemsTypeKey));
        if (type == 1) {
            if ("系统".equals(t) && CollectionUtil.isNotEmpty(systemArray)) {
                if (systemArray.size() > 1) {
                    return ResultUtil.error(500, "系统类型已可选择一种");
                }
                if (redisUtil.hasKey(typeKey)) {
                    Set targetSet = redisUtil.sGet(typeKey);
                    if (!targetSet.contains(systemArray.get(0))) {
                        return ResultUtil.error(500, "已选择系统类型，如需更改请删除类型后重试");
                    }
                }
                if (redisUtil.hasKey(targetKey)) {
                    Set targetSet = redisUtil.sGet(targetKey);
                    for (Object o : targetSet) {
                        String tId = redisUseService.getTargetTypeIdOrName(o.toString(), false);
                        for (String s : systemArray) {
                            if (!tId.equals(s)) {
                                return ResultUtil.error(500, "系统中仅可选择一种类型的目标进行添加");
                            }
                        }
                    }
                }
            }
            if ("系统".equals(t) && CollectionUtil.isNotEmpty(targetArray)) {
                Set targetSet = redisUtil.sGet(targetKey);
                for (String s : targetArray) {
                    String middleType = redisUseService.getTargetTypeIdOrName(s, false);
                    for (Object o : targetSet) {
                        String tId = redisUseService.getTargetTypeIdOrName(o.toString(), false);
                        if (!middleType.equals(tId)) {
                            return ResultUtil.error(500, "系统中尽可选择一种类型的目标进行添加");
                        }
                    }
                }
            }
            systemElseService.moveTarget(systemArray, typeKey, targetArray, targetKey, onKey);
        } else {
            systemElseService.pushTarget(typeKey, targetArray, targetKey, onKey);
        }
        return ResultUtil.success();
    }

    @Override
    public Result selectSystemConfirmTarget(Integer pageNum, Integer pageSize, String sysId, String keyword) {
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        //已选目标
        List<String> targetIds = new ArrayList<>();
        String key = keyWordSystem.getVERSION() + "systems" + sysId;
        if (redisUtil.hasKey(key)) {
            Set<Object> set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        //判断已选目标
        if (targetIds.isEmpty()) {
            resultMap.put("targetList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetData> targetDataList = systems.selectChoiceTarget(targetIds, keyword);
        PageInfo<TargetData> pageInfo = new PageInfo<>(targetDataList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (TargetData targetData : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("icon", StringUtils.isNotBlank(targetData.getIcon()) ? this.keyWordSystem.getSERVER_URL() + targetData.getIcon() : null);
                list.add(map);
            }
        }
        resultMap.put("targetList", list);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }


    @Override
    public Result selectSystemOnly(
            String sysId,
            String redId,
            String systemsName,
            String systemsType,
            String remark,
            String country,
            String keyword,
            String taskId,
            String systemType,
            boolean juage,
            String url,
            String countrys,
            String typeId
    ) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("sysId", sysId);
        resultMap.put("redId", redId);
        resultMap.put("systemsType", systemsType);
        resultMap.put("country", country);
        resultMap.put("keyword", keyword);
        resultMap.put("countrys", countrys);
        resultMap.put("typeId", typeId);
        //缓存类型选择列表key
        String typeKey = "systems_target_type_" + sysId;
        //缓存目标列表
        String targetKey = "system_list_" + sysId;
        //缓存已选独立目标列表
        String onKey = "system_target_list_" + sysId;
        //缓存体系集合类型
        String systemsTypeKey = "system_type_" + sysId;
        //查询当前体系key
        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
        //体系包含目标ID
        Set<Object> typeList = new HashSet<>();
        if (redisUtil.hasKey(typeKey)) {
            typeList = redisUtil.sGet(typeKey);
        }
        //系统ID列表
        Set<Object> targetSet = new HashSet<>();
        //初始化时将之前的目标放入缓存中
        if (juage) {
            redisUtil.del(typeKey, targetKey, onKey, systemsTypeKey);
            //以保存的目标列表加入缓存
            List<String> systemsTargetId = systemsRelationMapper.selectSystemsTargetId(sysId);
            if (CollectionUtil.isNotEmpty(systemsTargetId)) {
                for (String s : systemsTargetId) {
                    targetSet.add(s);
                }
            }
            if (CollectionUtil.isNotEmpty(targetSet)) {
                redisUtil.sSet(targetKey, targetSet.toArray());
            }
            //将以保存的已选类型/目标加入缓存
            List<SystemsElse> systemsElses = systemsElseService.lambdaQuery().eq(SystemsElse::getSysId, sysId).list();
            if (CollectionUtil.isNotEmpty(systemsElses)) {
                Set typeSet = new HashSet();
                Set onSet = new HashSet();
                for (SystemsElse els : systemsElses) {
                    if (els.getTypeValue() == 1) {
                        typeSet.add(els.getRelId());
                    } else {
                        targetSet.add(els.getRelId());
                        onSet.add(els.getRelId());
                    }
                }
                if (CollectionUtil.isNotEmpty(typeSet)) {
                    redisUtil.sSet(typeKey, typeSet.toArray());
                }
                if (CollectionUtil.isNotEmpty(onSet)) {
                    redisUtil.sSet(onKey, onSet.toArray());
                }
            } else if (CollectionUtil.isNotEmpty(targetSet)) {
                redisUtil.sSet(onKey, targetSet.toArray());
            }
        } else {
            //判断集合类型是否有修改
            if (StringUtils.isNotBlank(systemsType)) {
                if (!redisUtil.hasKey(systemsTypeKey)) {
                    redisUtil.set(systemsTypeKey, systemsType);
                } else {
                    //判断用户修改集合类型后清理之前以选择的所有信息
                    String t = redisUtil.get(systemsTypeKey).toString();
                    if (!t.equals(systemsType)) {
                        redisUtil.del(typeKey, targetKey, onKey);
                        redisUtil.set(systemsTypeKey, t);
                    }
                }
            }
            //获取缓存中目标列表
            if (redisUtil.hasKey(targetKey)) {
                targetSet = redisUtil.sGet(targetKey);
            }
        }

        if (ObjectUtil.isNotNull(systemsMaster)) {
            if (StringUtils.isBlank(countrys)) {
                resultMap.put("countrys", systemsMaster.getStat());
            }
//            if (StringUtils.isNotBlank(systemType)) {
//                resultMap.put("systemType", systemType);
//            } else if (StringUtils.isNotBlank(systemsMaster.getUserSign()) && systemsMaster.getUserSign().split("&&").length > 1) {
//                resultMap.put("systemType", systemsMaster.getUserSign().split("&&")[1]);
//            }
            resultMap.put("url", StringUtils.isNotBlank(url) ? url : StringUtils.isNotBlank(systemsMaster.getIcon()) ? systemsMaster.getIcon() : "");
            resultMap.put("systemsName", StringUtils.isNotBlank(systemsName) ? systemsName : systemsMaster.getSystemsName());
            resultMap.put("remark", StringUtils.isNotBlank(remark) ? remark : systemsMaster.getRemark());
            resultMap.put("redId", StringUtils.isNotBlank(redId) ? redId : systemsMaster.getRedId());
            resultMap.put("systemsType", StringUtils.isNotBlank(systemsType) ? systemsType : systemsMaster.getSystemsType());
            if (juage && StringUtils.isNotBlank(systemsMaster.getSystemsType())) {
                redisUtil.set(systemsTypeKey, systemsMaster.getSystemsType());
            }
        } else {
            resultMap.put("redId", redId);
            resultMap.put("systemType", systemType);
            resultMap.put("systemsName", systemsName);
            resultMap.put("remark", remark);
            resultMap.put("url", StringUtils.isNotBlank(url) ? url : "");
        }
        //TODO 查询系统列表 start
        List<Map<String, Object>> targetTypeList = systemElseService.selectTargetTypeList(typeList);
        //TODO 查询系统列表 end
        //TODO 查询类型下目标列表 start
        List<Map<String, Object>> typeTargetList = systemElseService.selectTypeTargetList(typeId, keyword, country, targetSet);
        //TODO 查询类型下目标列表 end
        //TODO 查询已选目标列表 start
        List<Map<String, Object>> selectTargetList = systemElseService.selectTargetList(typeKey, onKey);
        //TODO 查询已选目标列表 end
        //类型列表
        resultMap.put("systemList", targetTypeList);
        //类型下目标列表
        resultMap.put("targetList", typeTargetList);
        //已选目标列表
        resultMap.put("systemTargetList", selectTargetList);
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result addSystem(String sysId, String redId, String sysName, String typeId, String remark, String userId, String url, String country, String systemsType) {
        if (StringUtils.isBlank(sysId)) {
            return ResultUtil.error(500, "体系ID不能为空");
        }
        if (StringUtils.isBlank(redId)) {
            return ResultUtil.error(500, "父级不存在，请重新选择后重试");
        }
        if (StringUtils.isBlank(systemsType)) {
            return ResultUtil.error(500, "请选择集合类型");
        }
        if (StringUtils.isNotBlank(redId) && !redId.equals("0")) {
            if (systemsType.equals("体系")) {
                return ResultUtil.error(500, "下级集合，不可创建体系类型，请重新选择类型");
            }
            SystemsMaster master = systemsMasterMapper.selectOne(
                    new LambdaQueryWrapper<SystemsMaster>()
                            .eq(SystemsMaster::getSysId, redId)
            );
            if (ObjectUtil.isNotNull(master) && !master.getRedId().equals("0")) {
                return ResultUtil.error(500, "仅支持两级集合构建");
            }
        }
        if ("系统".equals(systemsType) && redisUtil.hasKey(RedisName.SYSTEMS_RELATION_LIST + "_" + sysId)) {
            return ResultUtil.error(500, "该集合下以包含系统，该类型只能选择体系");
        }
        //缓存类型选择列表key
        String typeKey = "systems_target_type_" + sysId;
        //缓存目标列表
        String targetKey = "system_list_" + sysId;
        //缓存已选独立目标列表
        String onKey = "system_target_list_" + sysId;
        //缓存体系集合类型
        String systemsTypeKey = "system_type_" + sysId;
        //目标关联保存
        Set<Object> targetIds = new HashSet<>();
        if (redisUtil.hasKey(targetKey)) {
            targetIds = redisUtil.sGet(targetKey);
        }
        //判断系统时类型只可选择一种
        if ("系统".equals(systemsType) && redisUtil.hasKey(typeKey)) {
            if (redisUtil.sGetSetSize(typeKey) > 1) {
                return ResultUtil.error(500, "系统只可选择一种类型进行添加");
            }
        }
        if ("系统".equals(systemsType) && redisUtil.hasKey(targetKey)) {
            Set targetSet = redisUtil.sGet(targetKey);
            String tId = null;
            for (Object id : targetSet) {
                String middleType = redisUseService.getTargetTypeIdOrName(id.toString(), false);
                if (null == tId) {
                    tId = middleType;
                } else {
                    if (!tId.equals(middleType)) {
                        return ResultUtil.error(500, "仅可选择一种类型的目标进行添加");
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(targetIds)) {
            //清理之前保存修改后不包含的目标
            List<String> relationNoTargets = systemsRelationMapper.selectRelationNoTargets(sysId, targetIds);
            if (CollectionUtil.isNotEmpty(relationNoTargets)) {
                for (String s : relationNoTargets) {
                    //关联关系
                    systemsRelationshipMapper.deleteShipOneTargetId(sysId, s);
                }
            }
            //删除不属于当前体系作用范围关联目标
            systemsRangeMapper.delete(new LambdaQueryWrapper<SystemsRange>()
                    .eq(SystemsRange::getSysId, sysId)
                    .notIn(SystemsRange::getTargetId, targetIds));
            systemsRangeTypeMapper.delete(new LambdaQueryWrapper<SystemsRangeType>()
                    .eq(SystemsRangeType::getSysId, sysId)
                    .notIn(SystemsRangeType::getTargetId, targetIds));
            //删除不属于当前体系攻防展示目标
            systemEmulateDataMapper.delete(new LambdaQueryWrapper<SystemEmulateData>()
                    .eq(SystemEmulateData::getSysId, sysId)
                    .notIn(SystemEmulateData::getTargetId, targetIds));
            //删除不属于当前体系分析目标
            systemsDynamicService
                    .lambdaUpdate()
                    .eq(SystemsDynamic::getSysId, sysId)
                    .in(SystemsDynamic::getTargetId, targetIds)
                    .remove();
            List<SystemsRelation> list = new ArrayList<>();
            SystemsRelation relation;
            for (Object targetId : targetIds) {
                relation = new SystemsRelation();
                relation.setSysRelId(snow.nextId() + "");
                relation.setSysId(sysId);
                relation.setTargetId(targetId.toString());
                relation.setTargetType("1");
                list.add(relation);
            }
            //清理之前的关联
            systems.deleteRelation(sysId);
            systems.addSystemsRelation(list);
            redisUseService.updateSystemsTarget(sysId, list);
        } else {
            //清理之前的关联
            systems.deleteRelation(sysId);
            redisUseService.deleteSystemsTargetList(sysId);
        }
        //体系类型和独立目标关联保存
        List<SystemsElse> systemsElses = new ArrayList<>();
        if (redisUtil.hasKey(typeKey)) {
            Set<Object> typeIds = redisUtil.sGet(typeKey);
            if (CollectionUtil.isNotEmpty(typeIds)) {
                for (Object id : typeIds) {
                    SystemsElse systemsElse = new SystemsElse();
                    systemsElse.setSysId(sysId);
                    systemsElse.setRelId(id.toString());
                    systemsElse.setTypeValue(1);
                    systemsElses.add(systemsElse);
                }
            }
        }
        if (redisUtil.hasKey(onKey)) {
            Set<Object> onIds = redisUtil.sGet(onKey);
            if (CollectionUtil.isNotEmpty(onIds)) {
                for (Object id : onIds) {
                    SystemsElse systemsElse = new SystemsElse();
                    systemsElse.setSysId(sysId);
                    systemsElse.setRelId(id.toString());
                    systemsElse.setTypeValue(2);
                    systemsElses.add(systemsElse);
                }
            }
        }
        systemsElseService.remove(new LambdaQueryWrapper<SystemsElse>().eq(SystemsElse::getSysId, sysId));
        if (CollectionUtil.isNotEmpty(systemsElses)) {
            systemsElseService.saveBatch(systemsElses);
        }
        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
        if (ObjectUtil.isNull(systemsMaster)) {
            systemsMaster = new SystemsMaster();
            systemsMaster.setSysId(sysId);
            systemsMaster.setCreateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
        systemsMaster.setRedId(redId);
        systemsMaster.setSystemsType(systemsType);
        systemsMaster.setStat(country);
        systemsMaster.setSystemsName(sysName);
        systemsMaster.setRemark(remark);
        systemsMaster.setUserSign(userId);
        systemsMaster.setIcon(url);
        systemsMaster.setIconUrl(url);
        systems.addSystem(systemsMaster);
        if (!"0".equals(redId)) {
            redisUseService.updateSystemsRelation(systemsMaster.getRedId(), systemsMaster);
        }
        redisUtil.del(typeKey, targetKey, onKey, systemsTypeKey);
        return ResultUtil.success("体系信息录入成功", null);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result deleteSystem(List<String> sysIds) {
        if (CollectionUtil.isNotEmpty(sysIds)) {
            for (String sysId : sysIds) {
                SystemsMaster master = systemsMasterMapper.selectById(sysId);
                if (ObjectUtil.isNotNull(master)) {
                    systems.deleteSystem(sysId);
                    asyncService.deleteSystemsAllBySysId(sysId);
                    if ("0".equals(master.getRedId())) {
                        redisUseService.deleteSystemsRelationAll(master.getSysId());
                        List<SystemsMaster> systemsMasters = systemsMasterMapper.selectList(new LambdaQueryWrapper<SystemsMaster>().eq(SystemsMaster::getRedId, sysId));
                        if (CollectionUtil.isNotEmpty(systemsMasters)) {
                            for (SystemsMaster systemsMaster : systemsMasters) {
                                asyncService.deleteSystemsAllBySysId(systemsMaster.getSysId());
                            }
                        }
                    } else {
                        redisUseService.deleteSystemsRelation(master.getRedId(), master.getSysId());
                    }
                }
            }
        }
        return ResultUtil.success("删除成功", null);
    }

//    private void deleteSystemsBySysId(String sysId) {
//        int count = systems.deleteSystem(sysId);
//        if (count > 0) {
//            //缓存类型选择列表key
//            String typeKey = "systems_target_type_" + sysId;
//            //缓存目标列表
//            String targetKey = "systemList" + sysId;
//            //缓存已选独立目标列表
//            String onKey = "systemTargetList" + sysId;
//            systems.deleteInfo(sysId);
//            systems.deleteShip(sysId);
//            systems.delSystemsElseData(sysId);
//            systems.deleteRelation(sysId);
//            systemsElseService.lambdaUpdate().eq(SystemsElse::getSysId, sysId).remove();
//            systemsRangeMapper.delete(new LambdaQueryWrapper<SystemsRange>().eq(SystemsRange::getSysId, sysId));
//            redisUtil.del(typeKey, targetKey, onKey);
//            redisUseService.deleteSystemsTargetList(sysId);
//        }
//    }

    @Override
    public Result selectSystemList(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<SystemsMaster> system = systems.selectSystemList(null, keyword);
        PageInfo<SystemsMaster> pageInfo = new PageInfo<>(system);
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (SystemsMaster systemsMaster : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("sysId", systemsMaster.getSysId());
                map.put("systemsName", systemsMaster.getSystemsName());
                String type = "";
                if (StringUtils.isNotBlank(systemsMaster.getIncludeType())) {
                    if (systemsMaster.getIncludeType().contains(",")) {
                        List<String> strings = Arrays.asList(systemsMaster.getIncludeType().split(","));
                        for (String string : strings) {
                            String typeName = targetMapper.getTypeName(string);
                            if (StringUtils.isNotBlank(typeName)) {
                                type += type.length() > 0 ? "," + typeName : typeName;
                            }
                        }
                    } else {
                        type = targetMapper.getTypeName(systemsMaster.getIncludeType());
                    }
                }
                map.put("includeType", type);
                map.put("include", systemsMaster.getInclude());
                map.put("icon", StringUtils.isNotBlank(systemsMaster.getIcon()) ? this.keyWordSystem.getSERVER_URL() + systemsMaster.getIcon() : null);
                resultList.add(map);
            }
        }
        resultMap.put("systemList", resultList);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }


    @Override
    public Result uploadTargetIcon(String targetId, String icon) {
        TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (null == targetData) {
            return ResultUtil.error(ResultEnum.EXTERNAL_TARGET_EMPTY);
        }
        String iconUrl = FileElseUtil.generateImage(icon, keyWordSystem.getFILE_URL() + "/icon");
        if (null != iconUrl) {
            if (StringUtils.isNotBlank(targetData.getIconUrl())) {
                FileUtil.del(keyWordSystem.getFILE_URL() + targetData.getIconUrl());
            }
            targetData.setIcon(iconUrl);
            targetData.setIconUrl(iconUrl);
            targetMapper.updateTargetIcon(targetData);
            return ResultUtil.success("上传成功", null);
        } else {
            return ResultUtil.error(ResultEnum.IMAGE_UPLOAD_ERROR);
        }
    }

    @Override
    public Result uploadSystemIcon(String sysId, String icon) {
        SystemsMaster systemsMaster = systems.selectSystemOnlyBySId(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_SYSTEM_EMPTY);
        }
        String iconUrl = FileElseUtil.generateImage(icon, keyWordSystem.getFILE_URL() + "/icon");
        if (null != iconUrl) {
            if (StringUtils.isNotBlank(systemsMaster.getIconUrl())) {
                FileUtil.del(systemsMaster.getIconUrl());
            }
            systemsMaster.setIcon(iconUrl.split("@@")[1]);
            systemsMaster.setIconUrl(iconUrl.split("@@")[0]);
            systems.updateSystemIcon(systemsMaster);
            return ResultUtil.success("上传成功", null);
        } else {
            return ResultUtil.error(ResultEnum.IMAGE_UPLOAD_ERROR);
        }
    }

    @Override
    public Result uploadRapexIcon(String sysId, String icon) {
        SystemsMaster systemsMaster = systems.selectOnlyBySId(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_RAPEX_EMPTY);
        }
        String iconUrl = FileElseUtil.generateImage(icon, keyWordSystem.getFILE_URL() + "/icon");
        if (null != iconUrl) {
            if (StringUtils.isNotBlank(systemsMaster.getIconUrl())) {
                FileUtil.del(systemsMaster.getIconUrl());
            }
            systemsMaster.setIcon(iconUrl.split("@@")[1]);
            systemsMaster.setIconUrl(iconUrl.split("@@")[0]);
            systems.updateIcon(systemsMaster);
            return ResultUtil.success("上传成功", null);
        } else {
            return ResultUtil.error(ResultEnum.IMAGE_UPLOAD_ERROR);
        }
    }


    /**
     * 更新统计属性
     */
    private void updateRedisInfoElement(Map<Object, Object> infoMap, String infoKey) {
        if (!infoKey.isEmpty()) {
            Map<String, Object> info = new HashMap<>();
            for (Map.Entry<Object, Object> objectObjectEntry : infoMap.entrySet()) {
                info.put(objectObjectEntry.getKey().toString(), objectObjectEntry.getValue());
            }
            if (redisUtil.hasKey(infoKey)) {
                redisUtil.del(infoKey);
            }
            redisUtil.hmset(infoKey, info, KeyWordSystem.REDIS_TIME);
        }
    }

    /**
     * 更新已选目标
     */
    private void updateRedisConfirmTarget(String sId, String key) {
//        String systemKey = keyWordSystem.getVERSION() + "systemList" + sId;
//        List<String> targetIds = new ArrayList<>();
//        Set<Object> set = new HashSet<>();
//        if (redisUtil.hasKey(key)) {
//            set = redisUtil.sGet(key);
//            for (Object o : set) {
//                targetIds.add(o.toString());
//            }
//        }
//        targetIds.addAll(systems.selectSystemRelationTargetId(sId));
//        for (String id : targetIds) {
//            set.add(id);
//        }
//        if (redisUtil.hasKey(systemKey) && CollectionUtil.isNotEmpty(redisUtil.sGet(systemKey))) {
//            List<String> list = new ArrayList<>();
//            for (Object s : redisUtil.sGet(systemKey)) {
//                list.add(s.toString());
//            }
//            List<String> targets = systemsRelationMapper.selectRelationTargetNameBySystemList(list);
//            if (CollectionUtil.isNotEmpty(targets)) {
//                for (String target : targets) {
//                    set.add(target);
//                }
//            }
//        }
//        if (redisUtil.hasKey(key)) {
//            redisUtil.del(key);
//        }
//        if (CollectionUtil.isNotEmpty(set)) {
//            redisUtil.sSetAndTime(key, keyWordSystem.REDIS_TIME, set.toArray());
//        }
        List<String> list = systems.selectSystemRelationTargetId(sId);
        if (CollectionUtil.isNotEmpty(list)) {
            Set<Object> set = new HashSet<>();
            for (String s : list) {
                set.add(s);
            }
            redisUtil.sSetAndTime(key, KeyWordSystem.REDIS_TIME, set.toArray());
        }
    }

    /**
     * 新增体系关系（单条）
     *
     * @param json
     * @return
     */
    @Override
    public Result<Map<String, Object>> addRelationship(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        if (StringUtils.isBlank(sysId) || StringUtils.isBlank(targetId)) {
            return ResultUtil.error(50003, ResultEnum.getByValue(50003));
        }
        String s = JSON.toJSONString(json.get("systemsRelationship"));
        List<SystemsRelationship> relationships = JSON.parseArray(s, SystemsRelationship.class);
        List<String> targetName = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(relationships)) {
            for (SystemsRelationship systemsRelationship : relationships) {
                if (targetName.contains(systemsRelationship.getTargetTwo())) {
                    continue;
                }
                if (!StringUtils.isNumeric(systemsRelationship.getRelationType())) {
                    continue;
                }
                targetName.add(systemsRelationship.getTargetTwo());
                if (StringUtils.isBlank(systemsRelationship.getSysShipId())) {
                    systemsRelationship.setSysShipId(snow.nextId() + "");
                }
                systemsRelationship.setSysId(sysId);
                systemsRelationship.setTargetOne(targetId);
                systemsRelationshipMapper.save(systemsRelationship);
            }
            return ResultUtil.success("体系关系保存成功");
        }
        return ResultUtil.error(50004, ResultEnum.getByValue(50004));
    }

    @Override
    public Result<Map<String, Object>> deleteRelationship(String sysShipId) {
        systemsRelationshipMapper.deleteBySysShipId(sysShipId);
        return ResultUtil.success("体系关系删除成功");
    }

    @Override
    public Result selectSystemDetail(String sysId, String targetId) {
        Map<String, Object> resultMap = new HashMap<>();
        ArrayList<JSONObject> returnList = new ArrayList<>();
        ArrayList<JSONObject> parentList = new ArrayList<>();
        ArrayList<JSONObject> childrenList = new ArrayList<>();
        if (StringUtils.isBlank(sysId)) {
            return ResultUtil.error(50003, ResultEnum.getByValue(50003));
        }
        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
        resultMap.put("sysId", systemsMaster.getSysId());
        resultMap.put("systemsName", systemsMaster.getSystemsName());
        resultMap.put("includeType", "");
        resultMap.put("include", systemsMaster.getInclude());
        resultMap.put("remark", systemsMaster.getRemark());
        List<SystemsRelation> systemsRelations = systemsRelationMapper.findById(sysId);
        resultMap.put("systemsRelation", systemsRelations);
        List<SystemsRelationship> systemsRelationships = null;
        if (StringUtils.isNotBlank(targetId)) {
            systemsRelationships = systemsRelationshipMapper.findBySysIdAndTargetOne(sysId, targetId);
        } else {
            systemsRelationships = systemsRelationshipMapper.findBySysId(sysId);
        }
        //当前体系所有关联目标
        List<String> systemsTargetList = redisUseService.getSystemsTargetList(sysId);

        if (CollectionUtil.isEmpty(systemsTargetList)) {
            systemsTargetList = new ArrayList<>();
        }

        Map<Object, Object> relation = redisUseService.getSystemsRelation(sysId);
        if (CollectionUtil.isNotEmpty(relation)) {
            for (Object id : relation.keySet()) {
                List<String> subIds = redisUseService.getSystemsTargetList(id.toString());
                if (CollectionUtil.isNotEmpty(subIds)) {
                    systemsTargetList.addAll(subIds);
                }
            }
        }
        Map<String, Set<String>> cMap = new HashMap<>();
        Map<String, String> tMap = new HashMap<>();
        LinkedHashSet lhs = new LinkedHashSet();
        for (SystemsRelationship targetRelation : systemsRelationships) {
            if (!systemsTargetList.contains(targetRelation.getTargetOne())
                    || !systemsTargetList.contains(targetRelation.getTargetTwo())) {
                continue;
            }
            if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + targetRelation.getTargetOne())
                    && redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + targetRelation.getTargetTwo())
            ) {

                String targetOneName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetRelation.getTargetOne(), "targetName").toString();
                String targetTwoName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetRelation.getTargetTwo(), "targetName").toString();
                JSONObject parent = new JSONObject();
                parent.put("name", targetOneName);
                JSONObject parentRelation = new JSONObject();
                parentRelation.put("name", targetTwoName);
                parentList.add(parentRelation);
                parentList.add(parent);

                JSONObject result = new JSONObject();
                result.put("sysShipId", targetRelation.getSysShipId());
                result.put("targetOne", targetRelation.getTargetOne());
                result.put("targetTwo", targetRelation.getTargetTwo());
                result.put("point", targetRelation.getPoint());
                result.put("relationType", targetRelation.getRelationType());
                returnList.add(result);
                //关系图
                String one = targetOneName + "&&" + targetTwoName;
                String two = targetTwoName + "&&" + targetOneName;
                if (null == cMap.get(one)) {
                    if (null == cMap.get(two)) {
                        if ("目标1指向目标2".equals(targetRelation.getPoint())) {
                            tMap.put(one, "1");
                        } else if ("目标2指向目标1".equals(targetRelation.getPoint())) {
                            tMap.put(one, "2");
                        } else {
                            tMap.put(one, "3");
                        }
                        Set<String> set = new HashSet<>();
                        set.add(targetRelation.getRelationType());
                        cMap.put(one, set);
                    } else {
                        Set<String> set = cMap.get(two);
                        set.add(targetRelation.getRelationType());
                        cMap.put(two, set);
                    }
                } else {
                    Set<String> set = cMap.get(one);
                    set.add(targetRelation.getRelationType());
                    cMap.put(one, set);
                }


//                JSONObject children = new JSONObject();
//                if ("目标1指向目标2".equals(targetRelation.getPoint())) {
//                    children.put("source", targetOneName);//父级名称
//                    children.put("target", targetTwoName);//子级名称
//                    children.put("value", targetRelation.getRelationType());//关系
//                } else if ("目标2指向目标1".equals(targetRelation.getPoint())) {
//                    children.put("source", targetTwoName);//子级名称
//                    children.put("target", targetOneName);//父级名称
//                    children.put("value", targetRelation.getRelationType());//关系
//                } else if ("互相指向".equals(targetRelation.getPoint())) {
//                    children.put("source", targetOneName);//父级名称
//                    children.put("target", targetTwoName);//子级名称
//                    children.put("value", targetRelation.getRelationType());//关系
//                    JSONObject childrenRelation = new JSONObject();
//                    childrenRelation.put("source", targetTwoName);//子级名称
//                    childrenRelation.put("target", targetOneName);//父级名称
//                    childrenRelation.put("value", "");//关系
//                    childrenList.add(childrenRelation);
//                }
//                childrenList.add(children);
            }
        }
        for (String s : tMap.keySet()) {
            JSONObject children = new JSONObject();
            if ("1".equals(tMap.get(s))) {
                children.put("source", s.split("&&")[0]);//父级名称
                children.put("target", s.split("&&")[1]);//子级名称
                Set<String> set = cMap.get(s);
                StringBuffer sb = new StringBuffer();
                int num = set.size();
                for (String str : set) {
                    if (1 == num) {
                        sb.append(str);
                    } else {
                        sb.append(str + "丨");
                    }
                    num--;
                }
                children.put("value", sb.toString());//关系
            } else if ("2".equals(tMap.get(s))) {
                children.put("source", s.split("&&")[1]);//父级名称
                children.put("target", s.split("&&")[0]);//子级名称
                Set<String> set = cMap.get(s);
                StringBuffer sb = new StringBuffer();
                int num = set.size();
                for (String str : set) {
                    if (1 == num) {
                        sb.append(str);
                    } else {
                        sb.append(str + "丨");
                    }
                    num--;
                }
                children.put("value", sb.toString());//关系
            } else {
                children.put("source", s.split("&&")[0]);//父级名称
                children.put("target", s.split("&&")[1]);//子级名称
                Set<String> set = cMap.get(s);
                StringBuffer sb = new StringBuffer();
                int num = set.size();
                for (String str : set) {
                    if (1 == num) {
                        sb.append(str);
                    } else {
                        sb.append(str + "丨");
                    }
                    num--;
                }
                children.put("value", sb.toString());//关系
                JSONObject childrenRelation = new JSONObject();
                childrenRelation.put("source", s.split("&&")[1]);//子级名称
                childrenRelation.put("target", s.split("&&")[0]);//父级名称
                childrenRelation.put("value", "");//关系
                childrenList.add(childrenRelation);
            }
            childrenList.add(children);
        }
        lhs.addAll(parentList);
        resultMap.put("systemsRelationship", returnList);
        resultMap.put("parentList", lhs);
        resultMap.put("childrenList", childrenList);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result selectIndexPull(String sId) {
        return ResultUtil.success("查询成功", systems.selectInfoList(sId));
    }

    @Override
    public Result selectSystemWaitList(int pageNum, int pageSize, String sysId, String index) {
        if (StringUtils.isBlank(sysId)) {
            return ResultUtil.error(ResultEnum.EXTERNAL_SYSTEM_EMPTY);
        }
        if (StringUtils.isNotBlank(index)) {
            return getInitSystemWaitDataListByIndex(pageNum, pageSize, sysId, index);
        }
        return getInitSystemWaitDataList(pageNum, pageSize, sysId);
    }

    /**
     * 查询待选目标指标排序列表
     */
    public Result getInitSystemWaitDataListByIndex(int pageNum, int pageSize, String sysId, String index) {
        SystemsMaster systemMaster = systems.selectSystemOnlyGetTypeIdBySId(sysId);
        if (null == systemMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_SYSTEM_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //根据类别查询目标
        List<String> typeIds = null;
        if (StringUtils.isNotBlank(systemMaster.getIncludeType())) {
            JSONArray objects = JSONArray.parseArray(systemMaster.getIncludeType());
            typeIds = new ArrayList<>();
            for (Object id : objects) {
                typeIds.add(id.toString());
            }
        }
        if (null == typeIds || typeIds.isEmpty()) {
            resultMap.put("waitList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        //筛选已经选择的目标
        List<String> confirmTarget = systems.selectSystemRelationTargetId(sysId);
        if (null == confirmTarget || confirmTarget.isEmpty()) {
            confirmTarget = null;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetIndexList> targetIndexLists = systems.selectWaitDataList(typeIds, confirmTarget, index, sysId);
        PageInfo<TargetIndexList> pageInfo = new PageInfo<>(targetIndexLists);
        resultMap.put("waitList", pageInfo.getList());
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    /**
     * 初始化待选系统详细信息列表
     */
    private Result getInitSystemWaitDataList(int pageNum, int pageSize, String sId) {
        SystemsMaster systemMaster = systems.selectSystemOnlyGetTypeIdBySId(sId);
        if (null == systemMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_SYSTEM_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //根据类别查询目标
        List<String> typeIds = null;
        if (StringUtils.isNotBlank(systemMaster.getIncludeType())) {
            List<String> strings = Arrays.asList(systemMaster.getIncludeType().split(","));
            for (String id : strings) {
                typeIds.add(id);
            }
        }
        if (CollectionUtil.isEmpty(typeIds)) {
            resultMap.put("waitList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        //筛选已经选择的目标
        List<String> confirmTarget = systems.selectSystemRelationTargetId(sId);
        if (null == confirmTarget || confirmTarget.isEmpty()) {
            confirmTarget = null;
        }
        //获取类别名称
        List<String> typeNames = null;
        for (String typeId : typeIds) {
            String typeName = systems.selectTypeName(typeId);
            typeNames.add(typeName);
            if (StringUtils.isBlank(typeName)) {
                typeName = "类别名称已删除，请重新选择";
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetData> targetDataList = systems.selectWaitChoiceTarget(typeIds, confirmTarget, null);
        PageInfo<TargetData> pageInfo = new PageInfo<>(targetDataList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (TargetData targetData : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("indexData", 0);
                map.put("typeName", typeNames);
                map.put("hitDegree", null);
                list.add(map);
            }
        }
        resultMap.put("waitList", list);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result insertConfirmIndex(List<SystemsRelation> list, String sysId, String status) {
        if (null == list || list.isEmpty()) {
            return ResultUtil.error(ResultEnum.UPDATE_EMPTY);
        }
        String indexKey = this.keyWordSystem.getVERSION() + "index" + sysId;
        List<String> targetList = new ArrayList<>();
        for (SystemsRelation systemRelation : list) {
            systemRelation.setSysId(sysId);
            systemRelation.setSysRelId(snow.nextId() + "");
            targetList.add(systemRelation.getTargetId());
        }
        if (status.equals("add")) {
            SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
            Integer include = systemsMaster.getInclude();
            systems.insertSystemsRelation(list);
            include += list.size();
            systemsMaster.setInclude(include);
            systems.updateSystemsInclude(systemsMaster);
        }
        List<TargetInfo> targetInfos = systems.selectConfirmIndexList(targetList);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (null != targetInfos && !targetInfos.isEmpty()) {
            for (TargetInfo targetInfo : targetInfos) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", targetInfo.getName() + "(" + targetInfo.getKey() + ")");
                map.put("number", targetInfo.getValue());
                if (redisUtil.hasKey(indexKey + targetInfo.getKey())) {
                    Double index = (Double) redisUtil.get(indexKey + targetInfo.getKey());
                    if (index == 0) {
                        map.put("value", 0);
                    } else if (targetInfo.getValue() >= index) {
                        map.put("value", 100);
                    } else {
                        map.put("value", (int) (targetInfo.getValue() / index * 100));
                    }
                } else {
                    map.put("value", 0);
                }
                redisUtil.set(sysId + map.get("name"), map.get("value"), KeyWordSystem.REDIS_TIME);
                resultList.add(map);
            }
        }
        return ResultUtil.success("添加成功", resultList);
    }

    @Override
    public Result selectSystemConfirmList(int pageNum, int pageSize, String sysId, String index) {
        return getInitSystemContirmDataList(pageNum, pageSize, sysId, index);
    }

    @Override
    public Result selectSystemIndexList(String sysId) {
        return getInitSystemWaitDataList(sysId);
    }

    @Override
    public Result selectSystemsIndexComparisonList(String sysId) {
        return getInitSystemComparisonDataList(sysId);
    }

    @Override
    public Result selectTypeList(String country, String sysId) {
        List<TargetType> list = targetMapper.selectSubType("1");
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.success(new ArrayList<>());
        }
        Set<Object> typeIndex = null;
        if (StringUtils.isNotBlank(sysId) && redisUtil.hasKey(SystemsServiceImpl.typeIndex + sysId)) {
            typeIndex = redisUtil.sGet(SystemsServiceImpl.typeIndex + sysId);
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (TargetType targetType : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("label", targetType.getTypeId());
            map.put("value", targetType.getTypeName());
            if (CollectionUtil.isNotEmpty(typeIndex)) {
                if (typeIndex.contains(targetType.getTypeId())) {
                    map.put("hidden", true);
                } else {
                    map.put("hidden", false);
                }
            } else {
                map.put("hidden", false);
            }
            map.put("children", new ArrayList<>());
            resultList.add(map);
        }
        if (StringUtils.isBlank(country)) {
            SystemsMaster systemsMaster = systems.findSystemsMasterById(sysId);
            if (null != systemsMaster && StringUtils.isNotBlank(systemsMaster.getStat())) {
                resultMap.put("country", systemsMaster.getStat());
            } else {
                resultMap.put("country", null);
            }
        } else {
            resultMap.put("country", country);
        }
        resultMap.put("typeList", resultList);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result selectSystemList(String sysId, List<String> typeList, String country) {
        Set<Object> systemList = null;
        if (StringUtils.isNotBlank(sysId) && redisUtil.hasKey(systemIndex + sysId)) {
            systemList = redisUtil.sGet(systemIndex + sysId);
        }
        if (StringUtils.isBlank(country)) {
            country = null;
        }
        if (CollectionUtil.isEmpty(typeList)) {
            typeList = null;
        } else {
            if (redisUtil.hasKey(typeIndex + sysId)) {
                redisUtil.del(typeIndex + sysId);
            }
            redisUtil.sSetAndTime(typeIndex + sysId, KeyWordSystem.REDIS_TIME, typeList.toArray());
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<SystemMaster> list = systems.selectSystemChooseList(country, typeList);
        if (CollectionUtil.isNotEmpty(systemList)) {
            if (systemList.contains("else")) {
                resultMap.put("else", true);
            } else {
                resultMap.put("else", false);
            }
        } else {
            resultMap.put("else", false);
        }
        if (CollectionUtil.isEmpty(list)) {
            resultMap.put("systemList", new ArrayList<>());
        } else {
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (SystemMaster systemMaster : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("lable", systemMaster.getSId());
                map.put("value", systemMaster.getSystemName());
                if (CollectionUtil.isNotEmpty(systemList)) {
                    if (systemList.contains(systemMaster.getSId())) {
                        map.put("hidden", true);
                    } else {
                        map.put("hidden", false);
                    }
                } else {
                    map.put("hidden", false);
                }
                map.put("children", new ArrayList<>());
                resultList.add(map);
            }
            resultMap.put("systemList", resultList);
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result selectSystemsElseData(String sysId) {
        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.SYSTEMS_IS_EXIST);
        }
        List<SystemsElseData> elseData = systems.selectSystemsElseDataList(sysId);
        if (CollectionUtil.isEmpty(elseData)) {
            return ResultUtil.success(new ArrayList<>());
        }
        Map<String, String> resultMap = new HashMap<>();
        for (SystemsElseData elseDatum : elseData) {
            resultMap.put(elseDatum.getKey(), elseDatum.getKeyValue());
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result addSystemsElseData(String sysId, List<SystemsElseData> list) {
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.error(ResultEnum.SYSTEMS_ELSE_NULL);
        }
        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.SYSTEMS_IS_EXIST);
        }
        for (SystemsElseData systemElseData : list) {
            systemElseData.setId(snow.nextId() + "");
            systemElseData.setSysId(sysId);
        }
        systems.delSystemsElseData(sysId);
        systems.addSystemsElseData(list);
        return ResultUtil.success("数据更新成功", null);
    }

    @Override
    public Result selectSystemConfirmTargetWuHan(Integer pageNum, Integer pageSize, String sysId, String targetId, String keyword) {
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        //已选目标
        List<String> targetIds = new ArrayList<>();
        targetIds.add(targetId);
        String key = keyWordSystem.getVERSION() + "systems" + sysId;
        if (redisUtil.hasKey(key)) {
            Set<Object> set = redisUtil.sGet(key);
            for (Object o : set) {
                targetIds.add(o.toString());
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        //判断已选目标
        if (targetIds.isEmpty()) {
            resultMap.put("targetList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetData> targetDataList = systems.selectChoiceTarget(targetIds, keyword);
        PageInfo<TargetData> pageInfo = new PageInfo<>(targetDataList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (TargetData targetData : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("icon", StringUtils.isNotBlank(targetData.getIcon()) ? this.keyWordSystem.getSERVER_URL() + targetData.getIcon() : null);
                list.add(map);
            }
        }
        resultMap.put("targetList", list);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public synchronized Result addSystemWuHan(SystemsAdd systemsAdd, String taskId) {
        if (StringUtils.isBlank(systemsAdd.getSysId())) {
            return ResultUtil.error(500, "体系ID不能为空");
        }
        if (StringUtils.isBlank(systemsAdd.getSystemsName())) {
            return ResultUtil.error(500, "体系名称不能为空");
        }
        //已选目标key
        String key = keyWordSystem.getVERSION() + "systems" + systemsAdd.getSysId();
        //统计属性key
        String infoKey = keyWordSystem.getVERSION() + "info" + systemsAdd.getSysId();
        //系统key
        String systemKey = keyWordSystem.getVERSION() + "systemList" + systemsAdd.getSysId();
        systems.deleteRelation(systemsAdd.getSysId());
        systems.deleteInfo(systemsAdd.getSysId());
        //目标数量
        int targetNum = 0;
        Set<Object> confirmTarget = redisUtil.sGet(key);
        if (null != confirmTarget && !confirmTarget.isEmpty()) {
            List<SystemsRelation> relations = new ArrayList<>();
            List<String> targets = new ArrayList<>();
            for (Object o : confirmTarget) {
                SystemsRelation relation = new SystemsRelation();
                relation.setSysRelId(snow.nextId() + "");
                relation.setSysId(systemsAdd.getSysId());
                relation.setTargetId(o.toString());
                relations.add(relation);
                targets.add(o.toString());
            }
            if (StringUtils.isNotBlank(systemsAdd.getTargetId())) {
                SystemsRelation relation = new SystemsRelation();
                relation.setSysRelId(snow.nextId() + "");
                relation.setSysId(systemsAdd.getSysId());
                relation.setTargetId(systemsAdd.getTargetId());
                relations.add(relation);
                targets.add(systemsAdd.getTargetId());
            }
            systems.deleteShipByList(systemsAdd.getSysId(), targets);
            targetNum = confirmTarget.size() + 1;
            systems.addSystemsRelation(relations);
        } else {
            List<SystemsRelation> relations = new ArrayList<>();
            if (StringUtils.isNotBlank(systemsAdd.getTargetId())) {
                SystemsRelation relation = new SystemsRelation();
                relation.setSysRelId(snow.nextId() + "");
                relation.setSysId(systemsAdd.getSysId());
                relation.setTargetId(systemsAdd.getTargetId());
                relations.add(relation);
                systems.addSystemsRelation(relations);
            }
            targetNum = 1;
        }
        //添加统计属性
        boolean juage = false;
        if (null != systemsAdd.getInfo() && !systemsAdd.getInfo().isEmpty()) {
            juage = true;
        }
        Map<Object, Object> infoMap = redisUtil.hmget(infoKey);
        if (null != infoMap && !infoMap.isEmpty()) {
            Map<String, Object> info = new HashMap<>();
            for (Map.Entry<Object, Object> objectObjectEntry : infoMap.entrySet()) {
                info.put(objectObjectEntry.getKey() + "", objectObjectEntry.getValue());
            }
            List<InfoElement> elements = new ArrayList<>();
            for (Map.Entry<String, Object> objectObjectEntry : info.entrySet()) {
                InfoElement element = new InfoElement();
                element.setId(snow.nextId() + "");
                element.setSysId(systemsAdd.getSysId());
                element.setKey(objectObjectEntry.getKey());
                element.setValue(objectObjectEntry.getValue().toString());
                if (juage) {
                    for (String s : systemsAdd.getInfo()) {
                        if (objectObjectEntry.getKey().equals(s)) {
                            element.setSign(1);
                            break;
                        }
                    }
                }
                if (null == element.getSign()) {
                    element.setSign(0);
                }
                elements.add(element);
            }
            systems.addInfoElement(elements);
        }
        SystemsMaster systemsMaster = new SystemsMaster();
        systemsMaster.setSysId(systemsAdd.getSysId());
        systemsMaster.setSystemsName(systemsAdd.getSystemsName());
        if (redisUtil.hasKey(systemKey)) {
            StringBuffer stringBuffer = new StringBuffer();
            for (Object o : redisUtil.sGet(systemKey)) {
                stringBuffer.append(o.toString());
            }
            systemsMaster.setIncludeType(stringBuffer.toString());
        }
        systemsMaster.setInclude(targetNum);
        systemsMaster.setRemark(systemsAdd.getRemark());
        systemsMaster.setTaskSign(taskId);
        systemsMaster.setStat(systemsAdd.getCountry());
        SystemsMaster old = systems.selectSystemsOnly(systemsAdd.getSysId());
        if (null != old) {
            systemsMaster.setIcon(old.getIcon());
            systemsMaster.setIconUrl(old.getIconUrl());
        }
        systems.addSystem(systemsMaster);
        redisUtil.del(key);
        redisUtil.del(infoKey);
        return ResultUtil.success("系统录入成功", null);
    }

    @Override
    public Result selectSystemListWuHan(Integer pageNum, Integer pageSize, String taskId, List<String> includeType, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<SystemsMaster> system = systems.selectListWuHan(taskId, includeType, keyword);
        PageInfo<SystemsMaster> pageInfo = new PageInfo<>(system);
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (SystemsMaster systemsMaster : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("sysId", systemsMaster.getSysId());
                map.put("systemsName", systemsMaster.getSystemsName());
                map.put("include", systemsMaster.getInclude());
                map.put("icon", StringUtils.isNotBlank(systemsMaster.getIcon()) ? this.keyWordSystem.getSERVER_URL() + systemsMaster.getIcon() : null);
                resultList.add(map);
            }
        }
        resultMap.put("systemList", resultList);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result createDoc(String sysId, String damage) {
//        if (StringUtils.isBlank(damage)) {
//            return ResultUtil.error(400, "毁伤效果分析,不能为空");
//        }
//        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
//        if (null == systemsMaster) {
//            return ResultUtil.error(ResultEnum.SYSTEMS_IS_EXIST);
//        }
//        List<SystemsElseData> elseData = systems.selectSystemsElseDataList(sysId);
//        if (CollectionUtil.isEmpty(elseData)) {
//            return ResultUtil.error(400, "功能分析暂未填写");
//        }
//        for (SystemsElseData elseDatum : elseData) {
//            if (elseDatum.getKey().equals("construture") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "体系构成分析,不能为空");
//            } else if (elseDatum.getKey().equals("trait") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "体系特点分析,不能为空");
//            } else if (elseDatum.getKey().equals("choose") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "选取分析,不能为空");
//            } else if (elseDatum.getKey().equals("vital") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "体系要害分析,不能为空");
//            } else if (elseDatum.getKey().equals("effect") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "体系毁伤效果分析,不能为空");
//            } else if (elseDatum.getKey().equals("analysis") && StringUtils.isBlank(elseDatum.getKeyValue())) {
//                return ResultUtil.error(400, "体系分析结论,不能为空");
//            }
//        }
//        //创建文件路径
//        FileUtil.mkdir(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sysId);
//        //删除之前文件
//        FileUtil.del(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sysId + File.separator + systemsMaster.getSystemsName() + ".doc");
//        try {
//            WordBean wordBean = new WordBean(false);
//            wordBean.createNewDocument();
//            wordBean.insertTitle("", -2, "\"" + systemsMaster.getSystemsName() + "\"" + "体系毁伤分析报告", 1);
//            wordBean.insertTitle("", -4, "1.体系构成分析", 0);
//            wordBean.insertText(getKeyValue("construture", elseData));
//            wordBean.insertTitle("", -4, "2.体系特点分析", 0);
//            wordBean.insertText(getKeyValue("trait", elseData));
//            wordBean.insertTitle("", -4, "3.选取分析", 0);
//            wordBean.insertText(getKeyValue("choose", elseData));
//            wordBean.insertTitle("", -4, "4.体系要害分析", 0);
//            wordBean.insertText(getKeyValue("vital", elseData));
//            wordBean.insertTitle("", -4, "5.体系毁伤效果分析", 0);
//            wordBean.insertText(getKeyValue("effect", elseData));
//            wordBean.insertTitle("", -4, "5.系统动态划分与管理", 0);
//            wordBean.insertText(getKeyValue("analysis", elseData));
//            wordBean.insertTitle("", -4, "6.体系分析结论", 0);
//            wordBean.insertText(damage);
//            wordBean.save(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sysId + File.separator + systemsMaster.getSystemsName() + ".doc");
//            wordBean.closeDocument();
//            wordBean.close();
//            return ResultUtil.success("报告生成成功", null);
//        } catch (Exception e) {
        return ResultUtil.error(500, "生成文档异常，请稍后重试。");
//        }
    }

    private String getKeyValue(String key, List<SystemsElseData> elseData) {
        for (SystemsElseData elseDatum : elseData) {
            if (elseDatum.getKey().equals(key)) {
                return elseDatum.getKeyValue();
            }
        }
        return "";
    }

    @Override
    public Result downDoc(String sysId) {
        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
        if (FileUtil.isFile(this.keyWordSystem.getFILE_URL() + File.separator + "doc" + File.separator + sysId + File.separator + systemsMaster.getSystemsName() + ".doc")) {
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("fileUrl", this.keyWordSystem.getSERVER_URL() + "/doc/" + sysId + "/" + systemsMaster.getSystemsName() + ".doc");
            return ResultUtil.success(resultMap);
        } else {
            return ResultUtil.error(400, "请先生成报告");
        }
    }

    @Override
    public Result selectTargetPull(String sysId, String targetId) {
        List<Map<String, Object>> list = new ArrayList<>();
        Set<String> targetIds = new HashSet<>();
        targetIds.add(targetId);
        getSystemsTargetIds(list, targetIds, sysId);
        if (redisUtil.hasKey(RedisName.SYSTEMS_RELATION_LIST + "_" + sysId)) {
            Map<Object, Object> relation = redisUseService.getSystemsRelation(sysId);
            for (Object o : relation.keySet()) {
                SystemsMaster system = JSONObject.parseObject(relation.get(o).toString(), SystemsMaster.class);
                getSystemsTargetIds(list, targetIds, system.getSysId());
            }
        }
//        SystemsMaster systemsMaster = systems.selectSystemsOnly(sysId);
//        if (null != systemsMaster) {
//            List<String> list = systemsRelationMapper.selectSystemsRelation(sysId, "1");
//            if (CollectionUtil.isNotEmpty(list)) {
//                List<TargetData> targetList = targetMapper.getTargetList(list);
//                if (CollectionUtil.isNotEmpty(targetList)) {
//                    for (TargetData targetData : targetList) {
//                        if (StringUtils.isNotBlank(targetId) && targetData.getTargetId().equals(targetId)) {
//                            continue;
//                        }
//                        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
//                        stringObjectHashMap.put("targetId", targetData.getTargetId());
//                        stringObjectHashMap.put("targetName", targetData.getTargetName());
//                        hashSet.add(stringObjectHashMap);
//                    }
//                }
//            }
//        }
        return ResultUtil.success(list);
    }

    private void getSystemsTargetIds(List<Map<String, Object>> list, Set<String> targetIds, String sysId) {
        if (redisUtil.hasKey(RedisName.SYSTEMS_TARGET_LIST + "_" + sysId)) {
            Map<String, Object> map;
            Set<Object> targetSet = redisUtil.sGet(RedisName.SYSTEMS_TARGET_LIST + "_" + sysId);
            for (Object id : targetSet) {
                if (targetIds.contains(id.toString())) {
                    continue;
                }
                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
                    map = new HashMap<>();
                    map.put("targetId", id);
                    map.put("targetName", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName"));
                    list.add(map);
                    targetIds.add(id.toString());
                }
            }
        }
    }

    @Override
    public boolean judgeSystemsName(String sysId, String systemName) {
        SystemsMaster master = systems.selectOne(new LambdaQueryWrapper<SystemsMaster>().ne(SystemsMaster::getRedId, 0)
                .eq(SystemsMaster::getSystemsName, systemName).last("LIMIT 1"));
        if (ObjectUtil.isNotNull(master) && !master.getSysId().equals(sysId)) {
            return true;
        }
        return false;
    }

    @Override
    public Result selectSystemsTargetPull(String sysId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        SystemsMaster systemsMaster = systemsMasterMapper.selectSystemsOnly(sysId);
        if (ObjectUtil.isNotEmpty(systemsMaster.getIncludeType())) {
            String[] split = systemsMaster.getIncludeType().split(",");
            List<String> strings = systemsRelationMapper.selectRelationTargetNameBySystemList(Arrays.asList(split));
            List<String> stringList = systemsRelationMapper.selectSystemsRelation(sysId, "1");
            if (CollectionUtil.isNotEmpty(strings) && CollectionUtil.isNotEmpty(stringList)) {
                strings.addAll(stringList);
            }
            if (CollectionUtil.isNotEmpty(strings)) {
                List<TargetData> targets = targetMapper.getTargets(strings);
                Map<String, Object> map = null;
                for (TargetData target : targets) {
                    map = new HashMap<>();
                    map.put("label", target.getTargetName());
                    map.put("value", target.getTargetId());
                    resultList.add(map);
                }
            }
        }
        return ResultUtil.success(resultList);
    }

    /**
     * 保留后面位数
     */
    private int SUFF = 2;

    @Override
    public Result addBlows(JSONObject json) {
        String sysId = json.getString("sysId");
        if (StringUtils.isBlank(sysId)) {
            return ResultUtil.error(500, "体系ID不能为空");
        }
        String targetId = json.getString("targetName");
        if (StringUtils.isBlank(targetId)) {
            return ResultUtil.error(500, "请选择目标信息");
        }
        String blowMessage = json.getString("blowMessage");
        if (StringUtils.isBlank(blowMessage)) {
            return ResultUtil.error(500, "请选择打击程度信息");
        }
        if (StringUtils.isNotBlank(sysId)) {
            blowMapper.deleteBlow(sysId);
            blowMapper.addBlow(targetId, sysId, blowMessage);
        }
        boolean v = false;
        double sign = 0D;
        if (blowMessage.equals("轻度毁伤")) {
            sign = 0.2;
        } else if (blowMessage.equals("中度毁伤")) {
            sign = 0.5;
        } else {
            sign = 0.8;
        }
        //评估信息
        Map<String, Object> resultMap = new HashMap<>();
        //DY目标ID
        List<Map<String, Object>> list = knowMapper.selectYHInit(sysId, null);
        if (CollectionUtil.isNotEmpty(list)) {
            v = true;
            Double d = 0D;
            Double t = 0D;
            Double f = 0D;
            Double k = 0D;
            Double q = 0D;
            Integer max = 0;
            for (Map<String, Object> maps : list) {
                Double value = Double.valueOf(maps.get("value").toString());
                switch (maps.get("kind").toString()) {
                    case "打击能力":
                        d = value;
                        break;
                    case "通讯能力":
                        t = value;
                        break;
                    case "防御能力":
                        f = value;
                        break;
                    case "抗灾能力":
                        k = value;
                        break;
                    case "起降能力":
                        q = value;
                        break;
                }
                if (value > max) {
                    max = value.intValue();
                }
            }
            if (max == 0) {
                max = 1;
            } else {
                max = max + 2;
            }
            //DY后
            if (StringUtils.isNotBlank(targetId)) {
                Double db = d > 0 ? d * sign : 0D;
                Double tb = t > 0 ? t * sign : 0D;
                Double fb = f > 0 ? f * sign : 0D;
                Double kb = k > 0 ? k * sign : 0D;
                Double qb = q > 0 ? q * sign : 0D;
                List<BigDecimal> asList = Arrays.asList(
                        new BigDecimal(d - db).setScale(SUFF, BigDecimal.ROUND_HALF_DOWN),
                        new BigDecimal(t - tb).setScale(SUFF, BigDecimal.ROUND_HALF_DOWN),
                        new BigDecimal(f - fb).setScale(SUFF, BigDecimal.ROUND_HALF_DOWN),
                        new BigDecimal(k - kb).setScale(SUFF, BigDecimal.ROUND_HALF_DOWN),
                        new BigDecimal(q - qb).setScale(SUFF, BigDecimal.ROUND_HALF_DOWN));
                resultMap.put("yData", asList);
                resultMap.put("inData", asList);
            } else {
                resultMap.put("yData", Arrays.asList(d, t, f, k, q));
                resultMap.put("inData", Arrays.asList(d, t, f, k, q));
            }
            resultMap.put("outData", Arrays.asList(d, t, f, k, q));
            List<Map<String, Object>> indicator = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                Map<String, Object> maps = new HashMap<>();
                switch (i) {
                    case 0:
                        maps.put("name", "打击能力");
                        maps.put("max", max);
                        break;
                    case 1:
                        maps.put("name", "通讯能力");
                        maps.put("max", max);
                        break;
                    case 2:
                        maps.put("name", "防御能力");
                        maps.put("max", max);
                        break;
                    case 3:
                        maps.put("name", "抗灾能力");
                        maps.put("max", max);
                        break;
                    case 4:
                        maps.put("name", "起降能力");
                        maps.put("max", max);
                        break;
                }
                indicator.add(maps);
            }
            resultMap.put("indicator", indicator);
            resultMap.put("barData", Arrays.asList(max, max, max, max, max));
        } else {
            List<Map<String, Object>> indicator = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                Map<String, Object> maps = new HashMap<>();
                switch (i) {
                    case 0:
                        maps.put("name", "打击能力");
                        maps.put("max", 100);
                        break;
                    case 1:
                        maps.put("name", "通讯能力");
                        maps.put("max", 100);
                        break;
                    case 2:
                        maps.put("name", "防御能力");
                        maps.put("max", 100);
                        break;
                    case 3:
                        maps.put("name", "抗灾能力");
                        maps.put("max", 100);
                        break;
                    case 4:
                        maps.put("name", "起降能力");
                        maps.put("max", 100);
                        break;
                }
                indicator.add(maps);
            }
            resultMap.put("indicator", indicator);
            resultMap.put("outData", Arrays.asList(0, 0, 0, 0, 0));
            resultMap.put("inData", Arrays.asList(0, 0, 0, 0, 0));
            resultMap.put("yData", Arrays.asList(0, 0, 0, 0, 0));
            resultMap.put("barData", Arrays.asList(100, 100, 100, 100, 100));
        }
        resultMap.put("xData", Arrays.asList("打击能力", "通讯能力", "防御能力", "抗灾能力", "起降能力"));
        //下
        Map<String, Object> maps = new HashMap<>();
        if (v) {
            maps.put("mbnlz", 10);
            maps.put("shnlz", new BigDecimal(10 - (10 * sign)).setScale(SUFF, BigDecimal.ROUND_HALF_DOWN));
            if (sign <= 0.2) {
                maps.put("remark", "对该体系造成轻度毁伤效果");
            } else if (sign <= 0.6) {
                maps.put("remark", "对该体系造成中度毁伤效果");
            } else if (sign <= 0.8) {
                maps.put("remark", "对该体系造成重度毁伤效果");
            }
        } else {
            maps.put("mbnlz", 10);
            maps.put("shnlz", 0);
            maps.put("remark", "暂无结论生成");
        }
        resultMap.put("targetinfolist", maps);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result selectSystemsTree(String keyword, JSONArray systemsType, JSONArray country) {
        LambdaQueryWrapper<SystemsMaster> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(keyword), SystemsMaster::getSystemsName, keyword)
                .eq(CollectionUtil.isNotEmpty(systemsType), SystemsMaster::getSystemsType, systemsType)
                .eq(CollectionUtil.isNotEmpty(country), SystemsMaster::getStat, country)
                .eq(SystemsMaster::getRedId, "0");
        List<SystemsMaster> masters = systemsMasterMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(masters)) {
            List<Map<String, Object>> systemsTree = new ArrayList<>();
            for (SystemsMaster master : masters) {
                systemsTree.add(getSystemsMainList(master, master.getSysId(), "体系".equals(master.getSystemsType()) ? 1 : 2));
            }
            return ResultUtil.success(systemsTree);
        }
        return ResultUtil.success(ListUtil.empty());
    }

    @Override
    public Result addSystemsScene(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        String viewPosition = json.getString("viewPosition");
        String viewRotation = json.getString("viewRotation");
        String id = "";
        if (StringUtils.isNotBlank(sysId) && StringUtils.isBlank(targetId)) {
            id = sysId;
        } else if (StringUtils.isNotBlank(sysId) && StringUtils.isNotBlank(targetId)) {
            id = targetId;
        } else {
            return ResultUtil.error(500, "请选择需要添加场景的对象");
        }
        SystemsScene scene = systemsSceneMapper.selectById(id);
        if (ObjectUtil.isNull(scene)) {
            scene = new SystemsScene();
            scene.setId(id);
            scene.setViewPosition(viewPosition);
            scene.setViewRotation(viewRotation);
            systemsSceneMapper.insert(scene);
        } else {
            scene.setViewPosition(viewPosition);
            scene.setViewRotation(viewRotation);
            systemsSceneMapper.updateById(scene);
        }
        redisUseService.addSystemsScene(id, JSON.toJSONString(scene));
        return ResultUtil.success();
    }

    @Override
    public Result getSystemsScene(JSONObject json) {
        String sysId = json.getString("sysId");
        String targetId = json.getString("targetId");
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNotBlank(sysId) && StringUtils.isBlank(targetId)) {
            redisUseService.getSystemsScene(sysId, resultMap);
        } else if (StringUtils.isNotBlank(sysId) && StringUtils.isNotBlank(targetId)) {
            if (redisUtil.hHasKey(RedisName.SYSTEMS_SCENE, targetId)) {
                redisUseService.getSystemsScene(targetId, resultMap);
            } else {
                redisUseService.getSystemsScene(targetId, resultMap);
                redisUseService.getViewData(resultMap, targetId, true);
            }
        }
        return ResultUtil.success(resultMap);
    }

    private Map<String, Object> getSystemsMainList(SystemsMaster systemsMaster, String mainId, Integer mainFiffType) {
        Map<String, Object> systemMap = new HashMap<>();
        systemMap.put("mainId", mainId);
        systemMap.put("mainFiffType", mainFiffType);
        systemMap.put("sysId", systemsMaster.getSysId());
        systemMap.put("systemsName", systemsMaster.getSystemsName());
        systemMap.put("diffType", "体系".equals(systemsMaster.getSystemsType()) ? 1 : 2);
        systemMap.put("remark", FileElseUtil.getObjectToString(systemsMaster.getRemark()));
        systemMap.put("levels", 1);
        //
        FontTable fontTable = redisUseService.getFont("体系名称");
        systemMap.put("fontName", fontTable.getFontName());
        systemMap.put("fontSize", fontTable.getFontSize());
        systemMap.put("fontColor", fontTable.getFontColor());
        redisUseService.getSystemsScene(systemsMaster.getSysId(), systemMap);
        List<Map<String, Object>> children = new ArrayList<>();
        getSystemsTargetList(mainId, mainFiffType, systemsMaster.getSysId(), 2, systemsMaster.getSysId(), children);
        //获取当前体系下的系统
        getSystemsRelation(mainId, mainFiffType, systemsMaster.getSysId(), systemsMaster.getSysId(), children);
//        children.add(getSystemPostureList(mainId, mainFiffType, systemsMaster.getSysId(), systemsMaster.getSysId()));
        systemMap.put("children", children);
        return systemMap;
    }

    private void getSystemsRelation(String mainId, Integer mainFiffType, String parentId, String sysId, List<Map<String, Object>> main) {
        Map<Object, Object> systemsRelation = redisUseService.getSystemsRelation(sysId);
        if (CollectionUtil.isNotEmpty(systemsRelation)) {
            List<Map<String, Object>> children;
            for (Object o : systemsRelation.keySet()) {
                SystemsMaster system = JSONObject.parseObject(systemsRelation.get(o).toString(), SystemsMaster.class);
                Map<String, Object> systemMap = new HashMap<>();
                systemMap.put("mainId", mainId);
                systemMap.put("mainFiffType", mainFiffType);
                systemMap.put("sysId", system.getSysId());
                systemMap.put("systemsName", system.getSystemsName());
                systemMap.put("diffType", 2);
                systemMap.put("levels", 2);
                redisUseService.getSystemsScene(system.getSysId(), systemMap);
                children = new ArrayList<>();
                getSystemsTargetList(mainId, mainFiffType, system.getSysId(), 3, system.getSysId(), children);
                systemMap.put("children", children);
                main.add(systemMap);
            }
        }
    }

    /**
     * 获取当前体系下目标
     *
     * @param sysId
     * @param children
     */
    private void getSystemsTargetList(String mainId, Integer mainFiffType, String parentId, int level, String sysId, List<Map<String, Object>> children) {
        List<String> targetList = redisUseService.getSystemsTargetList(sysId);
        if (CollectionUtil.isNotEmpty(targetList)) {
            //类型封装 start
            Map<String, List<Map<String, Object>>> type = new HashMap<>();
            List<Map<String, Object>> middle;
            for (String id : targetList) {
                if (!redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
                    continue;
                }
                String typeIdOrName = redisUseService.getTargetTypeIdOrName(id, true);
                if (null == type.get(typeIdOrName)) {
                    middle = new ArrayList<>();
                } else {
                    middle = type.get(typeIdOrName);
                }
                Map<String, Object> targetMap = new HashMap<>();
                targetMap.put("mainId", mainId);
                targetMap.put("mainFiffType", mainFiffType);
                targetMap.put("sysId", parentId);
                targetMap.put("targetId", id);
                targetMap.put("systemsName", FileElseUtil.getObjectToString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName")));
                targetMap.put("diffType", 4);
                targetMap.put("levels", level + 1);
                targetMap.put("position", redisUseService.getViewPosition(id));
                redisUseService.getSystemsScene(id, targetMap);
                //放入类型列表
                middle.add(targetMap);
                type.put(typeIdOrName, middle);
            }
            for (String typeName : type.keySet()) {
                Map<String, Object> typeMap = new HashMap<>();
                typeMap.put("mainId", mainId);
                typeMap.put("mainFiffType", mainFiffType);
                typeMap.put("sysId", parentId);
                typeMap.put("systemsName", typeName);
                typeMap.put("diffType", 6);
                typeMap.put("levels", level);
                redisUseService.getSystemsScene("000", typeMap);
                typeMap.put("children", type.get(typeName));
                children.add(typeMap);
            }
            //类型封装 end
        }
    }

    private Map<String, Object> getSystemPostureList(String mainId, Integer mainFiffType, String parentId, String sysId) {
        Map<String, Object> postureMap = new HashMap<>();
        postureMap.put("mainId", mainId);
        postureMap.put("mainFiffType", mainFiffType);
        postureMap.put("sysId", parentId);
        postureMap.put("systemsName", "态势目标");
        postureMap.put("position", new ArrayList<>());
        postureMap.put("height", 0);
        postureMap.put("viewDistances", new ArrayList<>());
        postureMap.put("diffType", 3);
        postureMap.put("levels", 2);
        redisUseService.getSystemsScene("000", postureMap);
        if (redisUtil.hasKey(RedisName.POSTURE_RELATION_LIST + "_" + sysId)) {
            List<Map<String, Object>> list = new ArrayList<>();
            Set<Object> set = redisUtil.sGet(RedisName.POSTURE_RELATION_LIST + "_" + sysId);
            Map<String, Object> postureSubMap;
            for (Object id : set) {
                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
                    postureSubMap = new HashMap<>();
                    postureSubMap.put("mainId", mainId);
                    postureSubMap.put("mainFiffType", mainFiffType);
                    postureSubMap.put("sysId", parentId);
                    postureSubMap.put("postureId", id);
                    postureSubMap.put("systemsName", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName"));
                    postureSubMap.put("position", redisUseService.getViewPosition(id.toString()));
                    redisUseService.getSystemsScene(id.toString(), postureSubMap);
                    postureSubMap.put("diffType", 5);
                    postureSubMap.put("levels", 3);
                    list.add(postureSubMap);
                }
            }
            postureMap.put("children", list);
        } else {
            postureMap.put("children", ListUtil.empty());
        }
        return postureMap;
    }

    /**
     * 初始化已选系统详细信息列表
     */
    private Result getInitSystemContirmDataList(int pageNum, int pageSize, String sId, String index) {
        SystemsMaster systemMaster = systems.selectSystemOnlyGetTypeIdBySId(sId);
        if (null == systemMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_SYSTEM_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //筛选已经选择的目标
        List<String> confirmTarget = systems.selectSystemRelationTargetId(sId);
        if (null == confirmTarget || confirmTarget.isEmpty()) {
            confirmTarget = null;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetIndexList> targetIndexLists = systems.selectConfirmDataList(confirmTarget, index, sId);
        PageInfo<TargetIndexList> pageInfo = new PageInfo<>(targetIndexLists);
        resultMap.put("confirmList", pageInfo.getList());
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    /**
     * 查询能力指标列表
     */
    private Result getInitSystemWaitDataList(String sysId) {
        String indexKey = this.keyWordSystem.getVERSION() + "index" + sysId;
        Map<String, Object> resultMap = new HashMap<>();
        SystemsMaster systemMaster = systems.selectSystemOnlyGetTypeIdBySId(sysId);
        resultMap.put("systemsName", systemMaster.getSystemsName());
        List<String> indexList = systems.selectInfoList(sysId);
        if (null == indexList || indexList.isEmpty()) {
            resultMap.put("indexList", new ArrayList<>());
        } else {
            List<String> typeIds = null;
            if (StringUtils.isNotBlank(systemMaster.getIncludeType())) {
                List<String> strings = Arrays.asList(systemMaster.getIncludeType().split(","));
                for (String id : strings) {
                    typeIds.add(id);
                }
            }
            List<InfoElement> infos = systems.selectInfoDataList(sysId);
            List<String> info = new ArrayList<>();
            if (null != infos && !infos.isEmpty()) {
                for (InfoElement infoElement : infos) {
                    info.add(infoElement.getKey());
                }
            }
            if ((null != typeIds && !typeIds.isEmpty()) &&
                    (null != info && !info.isEmpty())) {
                List<TargetInfo> data = systems.selectInfoAll(typeIds, info);
                if (null != data && !data.isEmpty()) {
                    List<Map<String, Object>> resultList = new ArrayList<>();
                    for (InfoElement infoElement : infos) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", infoElement.getValue());
                        boolean juage = false;
                        for (TargetInfo datum : data) {
                            if (infoElement.getKey().equals(datum.getKey())) {
                                map.put("number", datum.getValue());
                                map.put("index", 100);
                                map.put("value", 0);
                                juage = true;
                                break;
                            }
                        }
                        if (!juage) {
                            map.put("value", 0);
                            map.put("index", 0);
                            map.put("number", 0);
                        }
                        if (redisUtil.hasKey(indexKey + infoElement.getKey())) {
                            redisUtil.del(indexKey + infoElement.getKey());
                        }
                        redisUtil.set(indexKey + infoElement.getKey(), map.get("number"), KeyWordSystem.REDIS_TIME);
                        resultList.add(map);
                    }
                    resultMap.put("indexList", resultList);
                } else {
                    resultMap.put("indexList", new ArrayList<>());
                }
            } else {
                resultMap.put("indexList", new ArrayList<>());
            }
        }
        return ResultUtil.success("查询成功", resultMap);
    }

    /**
     * 查询能力对比指标列表
     */
    private Result getInitSystemComparisonDataList(String sysId) {
        String indexKey = this.keyWordSystem.getVERSION() + "index" + sysId;
        Map<String, Object> resultMap = new HashMap<>();
        SystemsMaster systemMaster = systems.selectSystemOnlyGetTypeIdBySId(sysId);
        resultMap.put("systemsName", systemMaster.getSystemsName());
        List<String> indexList = systems.selectInfoList(sysId);
        if (null == indexList || indexList.isEmpty()) {
            resultMap.put("indexList", new ArrayList<>());
        } else {
            List<String> typeIds = null;
            if (StringUtils.isNotBlank(systemMaster.getIncludeType())) {
                List<String> strings = Arrays.asList(systemMaster.getIncludeType().split(","));
                for (String id : strings) {
                    typeIds.add(id);
                }
            }
            List<InfoElement> infos = systems.selectInfoDataList(sysId);
            List<String> info = new ArrayList<>();
            if (null != infos && !infos.isEmpty()) {
                for (InfoElement infoElement : infos) {
                    info.add(infoElement.getKey());
                }
            }
            if ((null != typeIds && !typeIds.isEmpty()) &&
                    (null != info && !info.isEmpty())) {
                List<TargetInfo> data = systems.selectInfoAll(typeIds, info);
                if (null != data && !data.isEmpty()) {
                    List<Map<String, Object>> resultList = new ArrayList<>();
                    for (InfoElement infoElement : infos) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", infoElement.getValue());
                        boolean juage = false;
                        for (TargetInfo datum : data) {
                            if (infoElement.getKey().equals(datum.getKey())) {
                                map.put("number", datum.getValue());
                                map.put("index", 100);
                                if (redisUtil.hasKey(sysId + map.get("name"))) {
                                    map.put("value", redisUtil.get(sysId + map.get("name")));
                                    redisUtil.del(sysId + map.get("name"));
                                } else {
                                    map.put("value", 0);
                                }
                                juage = true;
                                break;
                            }
                        }
                        if (!juage) {
                            map.put("value", 0);
                            map.put("index", 0);
                            map.put("number", 0);
                        }
                        if (redisUtil.hasKey(indexKey + infoElement.getKey())) {
                            redisUtil.del(indexKey + infoElement.getKey());
                        }
                        redisUtil.set(indexKey + infoElement.getKey(), map.get("number"), KeyWordSystem.REDIS_TIME);
                        resultList.add(map);
                    }
                    resultMap.put("indexList", resultList);
                } else {
                    resultMap.put("indexList", new ArrayList<>());
                }
            } else {
                resultMap.put("indexList", new ArrayList<>());
            }
        }
        return ResultUtil.success("查询成功", resultMap);
    }

}
